<template>
  <div>
    <h1>待办</h1>
    <input type="text" placeholder="请输入待办事项" v-model="newTodoText" @keyup.enter="addTodo" />
    <button @click="addTodo">添加</button>
    <hr />
    <span class="left" @click="set('done')">已完成{{ todos.filter(todo => todo.done).length }}条</span>
    <span class="right" @click="set('undone')">未完成{{ todos.filter(todo => !todo.done).length }}条</span>
    <span class="center" @click="set('all')">全部{{ todos.length }}条</span>
    <hr />
    <ul>
      <li v-for="(todo, index) in filteredTodos" :key="todo.id">
        <input type="checkbox" :checked="todo.done" @change="toggleTodo(index)" />
        <span :style="{ textDecoration: todo.done ? 'line-through' : 'none' }">{{ todo.text }}</span>
        <button @click="deleteTodo(index)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue'

interface Todo {
  id: number
  text: string
  done: boolean
}

const todos = ref<Todo[]>([
  { id: 1, text: '吃饭', done: false },
  { id: 2, text: '睡觉', done: false },
  { id: 3, text: '打豆豆', done: true },
  { id: 4, text: '学习', done: false },
])

const newTodoText = ref('')

function addTodo() {
  if (newTodoText.value.trim()) {
    todos.value.push({ id: Date.now(), text: newTodoText.value.trim(), done: false })
    newTodoText.value = ''
  }
}

function toggleTodo(index: number) {
  todos.value[index].done = !todos.value[index].done
}

function deleteTodo(index: number) {
  todos.value.splice(index, 1)
}

const list = ref('all')

function set(txt: string) {
  list.value = txt
}

const filteredTodos = computed(() => {
  switch (list.value) {
    case 'done':
      return todos.value.filter(todo => todo.done)
    case 'undone':
      return todos.value.filter(todo => !todo.done)
    default:
      return todos.value
  }
})

watch(todos, (newTodos) => {
  localStorage.setItem('todos', JSON.stringify(newTodos))
}, { deep: true })

onMounted(() => {
  const storedTodos = localStorage.getItem('todos')
  if (storedTodos) {
    todos.value = JSON.parse(storedTodos)
  }
})
</script>

<style scoped>
h1 {
  text-align: center;
}
input[type="text"] {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: none;
  border-radius: 5px;
}
button {
  padding: 10px;
  margin-bottom: 10px;
  border: none;
  border-radius: 5px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}
ul {
  list-style: none;
  padding: 0;
}
li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
li input[type="checkbox"] {
  margin-right: 10px;
}
li button {
  background-color: #f44336;
  color: white;
}
.left, .right,.center {
  display: inline-block;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
}
</style>